<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 书本详情
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-select v-model="query.province" placeholder="省" clearable filterable class="handle-select mr10" @change="listAllCity">
          <el-option
              v-for="item in provinceOptions"
              :key="item.code"
              :label="item.value"
              :value="item">
          </el-option>
        </el-select>
        <el-select v-model="query.city" clearable filterable placeholder="市" class="handle-select mr10" @change="listAllDistrict">
          <el-option
              v-for="item in cityOptions"
              :key="item.code"
              :label="item.value"
              :value="item">
          </el-option>
        </el-select>
        <el-select v-model="query.district" clearable filterable placeholder="区（县）" class="handle-select mr10">
          <el-option
              v-for="item in districtOptions"
              :key="item.code"
              :label="item.value"
              :value="item">
          </el-option>
        </el-select>
        <el-select v-model="query.gradeIdList" clearable multiple filterable placeholder="年级" class="handle-select mr10">
          <el-option
              v-for="item in gradeOptions"
              :key="item.code"
              :label="item.value"
              :value="item.code">
          </el-option>
        </el-select>
        <el-select v-model="query.subjectIdList" clearable multiple filterable placeholder="科目" class="handle-select mr10">
          <el-option
              v-for="item in subjectOptions"
              :key="item.code"
              :label="item.value"
              :value="item.code">
          </el-option>
        </el-select>
        <el-select v-model="query.status" clearable filterable placeholder="状态" class="handle-select mr10">
          <el-option
              v-for="item in statusOptions"
              :key="item.code"
              :label="item.value"
              :value="item.code">
          </el-option>
        </el-select>
        <el-date-picker
              placeholder="开始日期"
              type="datetime"
              v-model="query.startTime"
              class="handle-select mr10"
              style="width: 20%;"
        ></el-date-picker>
        <el-date-picker
            placeholder="结束日期"
            type="datetime"
            v-model="query.endTime"
            class="handle-select mr10"
            style="width: 20%;"
        ></el-date-picker>
      </div>
      <div class="handle-box">
        <el-input placeholder="请输入内容" v-model="query.searchValue" class="handle-input mr10">
          <el-select v-model="query.searchType" slot="prepend" placeholder="请选择" class="handle-select">
            <el-option label="ISBN" value="1"></el-option>
            <el-option label="书名" value="2"></el-option>
            <el-option label="上报人" value="3"></el-option>
          </el-select>
        </el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh-right" @click="resetQuery">重置</el-button>
        <el-button type="primary" icon="el-icon-upload" @click="reportBatchVisible = true">批量上报</el-button>
        <el-button type="primary" icon="el-icon-upload" @click="updateStatusBatchVisible = true">批量到工厂</el-button>
        <el-button type="primary" icon="el-icon-download" @click="exportVisible = true">导出</el-button>
      </div>
      <el-table
          :data="tableData"
          height="550"
          border
          class="table"
          ref="multipleTable"
          header-cell-class-name="table-header"
          @selection-change="handleSelectionChange"
      >
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="isbn" label="ISBN"></el-table-column>
        <el-table-column prop="bookName" label="书名"></el-table-column>
        <el-table-column label="学段" width="185">
          <template slot-scope="scope">
            <el-col><b>学段: </b>{{scope.row.sectionName}}</el-col>
            <el-col><b>年级: </b>{{scope.row.gradeName}}</el-col>
            <el-col><b>学科: </b>{{scope.row.subjectName}}</el-col>
            <el-col><b>学期: </b>{{scope.row.termName}}</el-col>
          </template>
        </el-table-column>
        <el-table-column label="地址" width="165">
          <template slot-scope="scope">
            <el-col><b>门店所在省: </b>{{scope.row.storeProvince}}</el-col>
            <el-col><b>门店所在市: </b>{{scope.row.storeCity}}</el-col>
            <el-col><b>门店所在区: </b>{{scope.row.storeDistrict}}</el-col>
          </template>
        </el-table-column>
        <el-table-column label="上报人" width="165">
          <template slot-scope="scope">
            <el-col><b>门店: </b>{{scope.row.storeName}}</el-col>
            <el-col><b>导购: </b>{{scope.row.shoppingGuideName}}</el-col>
            <el-col><b>上报人身份: </b>{{scope.row.reporter}}</el-col>
          </template>
        </el-table-column>
        <el-table-column label="图片" align="center" width="185">
          <template slot-scope="scope">
            <el-image
                class="table-td-thumb"
                v-for="item in [scope.row.coverUrl,scope.row.backCoverUrl,scope.row.infoCoverUrl]"
                :src="item"
                :preview-src-list="[scope.row.coverUrl,scope.row.backCoverUrl,scope.row.infoCoverUrl]"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="165">
          <template slot-scope="scope">
            <p v-if="scope.row.status===0">已购买邮寄中</p>
            <p v-if="scope.row.status===1">已到工厂</p>
            <p v-if="scope.row.status===2">已入库</p>
          </template>
        </el-table-column>
        <el-table-column  label="结果详情"  width="255">
          <template slot-scope="scope">
            <p><b>创建时间：</b>{{$moment(new Date(scope.row.createTime)).format("YYYY-MM-DD HH:mm:ss")}}</p>
            <p><b>修改时间：</b>{{$moment(new Date(scope.row.modifyTime)).format("YYYY-MM-DD HH:mm:ss")}}</p>
          </template>
        </el-table-column>
<!--        <el-table-column label="操作" width="180" align="center">-->
<!--          <template slot-scope="scope">-->
<!--            <el-button-->
<!--                type="text"-->
<!--                icon="el-icon-edit"-->
<!--                @click="handleEdit(scope.$index, scope.row)"-->
<!--            >编辑</el-button>-->
<!--            <el-button-->
<!--                type="text"-->
<!--                icon="el-icon-delete"-->
<!--                class="red"-->
<!--                @click="handleDelete(scope.$index, scope.row)"-->
<!--            >删除</el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
      <div class="pagination">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="query.pageNumber"
            :page-sizes="[10,20, 30, 50, 100]"
            :page-size="query.pageSize"
            :total="pageTotal"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
        ></el-pagination>
      </div>
    </div>

    <el-dialog title="批量到工厂" :visible.sync="updateStatusBatchVisible">
      <el-form :model="form">
        <el-upload
            ref="updateStatusBatchUpload"
            class="upload-demo"
            action="/book/v1/file/uploadFile"
            name="multipartFile"
            :before-upload="beforeUpload"
            :on-success="onSuccess_updateStatusBatch"
            :limit="1"
            :file-list="updateStatusBatchData.fileList">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传xls或xlsx文件，且不超过5MB,<a href="https://server-questionlibrary-oss.eebbk.net/questionlibrary/file/2020/09/14/1730/2/d2347dfb919c2def6c3ac57d9ef0dc7b.xlsx">下载模板</a></div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateStatusBatchVisible = false;$refs.updateStatusBatchUpload.clearFiles();">取 消</el-button>
        <el-button ref="updateStatusBatchButton" type="primary" @click="updateStatusBatch" disabled>确 定</el-button>
      </div>
    </el-dialog>
    <!-- 批量上报弹出框 -->
    <el-dialog title="批量上报" :visible.sync="reportBatchVisible" width="30%">
      <el-form :model="form">
        <el-upload
            ref="reportBatchUpload"
            class="upload-demo"
            action="/book/v1/file/uploadFile"
            name="multipartFile"
            :before-upload="beforeUpload"
            :on-success="onSuccess_reportBatch"
            :limit="1"
            :file-list="reportBatchData.fileList">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传xls或xlsx文件，且不超过5MB,<a href="https://server-questionlibrary-oss.eebbk.net/questionlibrary/file/2020/09/14/1730/2/d2347dfb919c2def6c3ac57d9ef0dc7b.xlsx">下载模板</a></div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reportBatchVisible = false;$refs.updateStatusBatchUpload.clearFiles();">取 消</el-button>
        <el-button ref="reportBatchButton" type="primary" @click="reportBatch" disabled>确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="导出" :visible.sync="exportVisible" width="30%">
      <p>确定导出这{{pageTotal}}条数据</p>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exportVisible = false">取 消</el-button>
        <el-button type="primary" @click="exportData">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listAllBookGrade,
  listAllCity,
  listAllDistrict,
  listAllProvince,
  listAllSubject, bookDetails, insertFileTask
} from "@/api/bookservice";
export default {
  name: 'basetable',
  data() {
    return {
      query: {
        province: {},
        city: {},
        district: {},
        status: null,
        gradeIdList: [],
        subjectIdList: [],
        startTime:null,
        endTime:null,
        pageNumber: 1,
        pageSize: 10,
        searchType:"1",
        searchValue:""
      },
      updateStatusBatchData:{
        fileList:[],
        param:{
          fileName:null,
          fileUrl:null,
          taskType:2,
          operationType:1,
          conditions:'{status:1}',
          creator:localStorage.getItem('ms_username')
        }
      },
      reportBatchData:{
        fileList:[],
        param:{
          fileName:null,
          fileUrl:null,
          taskType:3,
          operationType:1,
          conditions:'{status:0}',
          creator:localStorage.getItem('ms_username')
        }
      },
      provinceOptions: [],
      cityOptions: [],
      districtOptions: [],
      gradeOptions: [],
      subjectOptions: [],
      statusOptions:[
        {
          code:0,
          value:"已购买邮寄中"
        },
        {
          code:1,
          value:"已到工厂"
        },
        {
          code:2,
          value:"已入库"
        }
      ],
      tableData: [],
      multipleSelection: [],
      delList: [],
      reportBatchVisible: false,
      updateStatusBatchVisible: false,
      exportVisible: false,
      pageTotal: 0,
      form: {},
      idx: -1,
      id: -1
    };
  },
  created() {
    this.listAllProvince();
    this.listAllBookGrade();
    this.listAllSubject();
    this.getData();
  },
  methods: {
    // 获取 easy-mock 的模拟数据
    getData() {
      let param = {
        "startTime": this.query.startTime,
        "endTime": this.query.endTime,
        "gradeIdList": this.query.gradeIdList,
        "idList": [],
        "subjectIdList": this.query.subjectIdList,
        "isbnList": [],
        "pageNumber": this.query.pageNumber,
        "pageSize": this.query.pageSize,
        "status": this.query.status,
        "storeCity": this.query.city.value,
        "storeDistrict": this.query.district.value,
        "storeProvince": this.query.province.value
      };
      if(this.query.searchValue){
        switch (this.query.searchType) {
          case "1":
            //isbn
            let value = this.query.searchValue;
            let flag = /[,，;；\s\t\n]+/;
            let isbnList = value.split(flag);
            param.isbnList = isbnList;
            break;
          case "2":
            //书名
            let bookName = this.query.searchValue;
            param.bookName = bookName;
            break;
          case "3":
            //上报人
            let shoppingGuideName = this.query.searchValue;
            param.shoppingGuideName = shoppingGuideName;
            break;
        }
      }
      bookDetails(param).then((res) => {
        this.tableData = res.data.list;
        this.pageTotal = res.data.total || 0;
      });
    },
    updateStatusBatch(){
      this.updateStatusBatchVisible = false;
      this.$refs.updateStatusBatchUpload.clearFiles();
      insertFileTask(this.updateStatusBatchData.param).then((res) => {
        let code = res.code;
        let msg = res.data;
        if(code === 200){
          this.$message.success(msg);
        }else {
          this.$message.error(msg);
        }
      });
    },
    reportBatch(){
      this.reportBatchVisible = false;
      this.$refs.reportBatchUpload.clearFiles();
      insertFileTask(this.reportBatchData.param).then((res) => {
        let code = res.code;
        let msg = res.data;
        if(code === 200){
          this.$message.success(msg);
        }else {
          this.$message.error(msg);
        }
      });
    },
    exportData(){
      this.exportVisible = false;
      let conditions = {
        "startTime": this.query.startTime,
        "endTime": this.query.endTime,
        "gradeIdList": this.query.gradeIdList,
        "idList": [],
        "subjectIdList": this.query.subjectIdList,
        "isbnList": [],
        // "pageNumber": this.query.pageNumber,
        // "pageSize": this.query.pageSize,
        "status": this.query.status,
        "storeCity": this.query.city.value,
        "storeDistrict": this.query.district.value,
        "storeProvince": this.query.province.value
      };
      if(this.query.searchValue){
        switch (this.query.searchType) {
          case "1":
            //isbn
            let value = this.query.searchValue;
            let flag = /[,，;；\s\t\n]+/;
            let isbnList = value.split(flag);
            conditions.isbnList = isbnList;
            break;
          case "2":
            //书名
            let bookName = this.query.searchValue;
            conditions.bookName = bookName;
            break;
          case "3":
            //上报人
            let shoppingGuideName = this.query.searchValue;
            conditions.shoppingGuideName = shoppingGuideName;
            break;
        }
      }
      let param = {
        fileName:"书本信息导出",
        fileUrl:null,
        taskType:1,
        operationType:2,
        conditions:JSON.stringify(conditions),
        creator:localStorage.getItem('ms_username')
      }
      insertFileTask(param).then((res) => {
        let code = res.code;
        let msg = res.data;
        if(code === 200){
          this.$message.success(msg);
        }else {
          this.$message.error(msg);
        }
      });
    },
    onSuccess_updateStatusBatch(response, file, fileList){
      file.size;
      this.updateStatusBatchData.param.fileName = file.name;
      this.updateStatusBatchData.param.fileUrl = response.data;
      this.$refs.updateStatusBatchButton.disabled = false;
    },
    onSuccess_reportBatch(response, file, fileList){
      file.size;
      this.reportBatchData.param.fileName = file.name;
      this.reportBatchData.param.fileUrl = response.data;
      this.$refs.reportBatchButton.disabled = false;
    },
    // 触发搜索按钮
    handleSearch() {
      this.$set(this.query, 'pageNumber', 1);
      this.getData();
    },
    // 删除操作
    handleDelete(index, row) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
          .then(() => {
            this.$message.success('删除成功');
            this.tableData.splice(index, 1);
          })
          .catch(() => {});
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 编辑操作
    handleEdit(index, row) {
      this.idx = index;
      this.form = row;
      this.editVisible = true;
    },
    // 保存编辑
    saveEdit() {
      this.editVisible = false;
      this.$message.success(`修改第 ${this.idx + 1} 行成功`);
      this.$set(this.tableData, this.idx, this.form);
    },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, 'pageNumber', val);
      this.getData();
    },
    // 分页导航
    handleSizeChange(val) {
      this.$set(this.query, 'pageSize', val);
      this.getData();
    },
    // 查询所有的省
    listAllProvince(){
      listAllProvince().then((res) => {
        this.provinceOptions = res.data;
      });
    },
    listAllCity(){
      if(this.query.province){
        let param = {"province":this.query.province.value};
        listAllCity(param).then((res) => {
          this.cityOptions = res.data;
        });
      }
    },
    listAllDistrict(){
      if(this.query.province && this.query.city){
        let param = {"province":this.query.province.value,"city":this.query.city.value};
        listAllDistrict(param).then((res) => {
          this.districtOptions = res.data;
        });
      }
    },
    listAllBookGrade(){
      listAllBookGrade().then((res) => {
        let temp = [];
        for (let obj of res.data) {
          temp.push({"value":obj.gradeValue,"code":obj.gradeId});
        }
        this.gradeOptions = temp;
      });
    },
    listAllSubject(){
      listAllSubject().then((res) => {
        let temp = [];
        for (let obj of res.data) {
          temp.push({"value":obj.subjectValue,"code":obj.subjectId});
        }
        this.subjectOptions = temp;
      },);
    },
    beforeUpload(file){ // 上传前 文件校验
      //this.files = file;
      const xls = file.name.endsWith(".xls")
      const xlsx = file.name.endsWith(".xlsx")
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!xls && !xlsx) {
        this.$message.warning('上传文件只能是 xls、xlsx格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.warning('上传文件大小不能超过 5MB!')
        return false
      }
      //this.fileName = file.name;
      return true // 返回false不会自动上传
    },
    resetQuery(){
      this.query =  this.$options.data().query;
    }
  }
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 600px;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.mr20 {
  margin-right: 20px;
}
.table-td-thumb {
  display: inline-block;
  margin: 5px 5px 5px 5px;
  width: 40px;
  height: 40px;
}
.el-select .el-input {
  width: 130px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
</style>
